<template>
    <div class="grade-model-detial">
        <Card>
            <Collapse v-model="openPanel">
                <Panel name="1">
                    评分模型
                    <div class="content" slot="content">
                        <Form :model="pageParams" :label-width="120" :disabled="true">
                            <Row>
                                <Col span="8">
                                    <FormItem label="模型名称" prop="modelName">
                                        <Input v-model=" pageParams.modelName" placeholder />
                                    </FormItem>
                                </Col>
                                <Col span="8">
                                    <FormItem label="模型类型" prop="modelType">
                                        <Select v-model="pageParams.modelType" placeholder>
                                            <Option
                                                v-for="(item,index) in dataDict.gradeModelTypeDict"
                                                :key="index"
                                                :value="item.value"
                                            >{{item.title}}</Option>
                                        </Select>
                                    </FormItem>
                                </Col>
                                <Col span="8">
                                    <FormItem label="模型总分" prop="modelScore">
                                        <Input v-model=" pageParams.modelScore" placeholder />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </div>
                </Panel>
                <Panel name="2">
                    模型信息预览
                    <div class="content" slot="content">
                        <Table row-key="_idx" ref="currentRowTable" highlight-row :columns="tableHead" :data="tableData" :loading="loading">
                            <template slot-scope="{ row, index }" slot="elementName">
                                <a v-if="row.elementType === '1'" @click="change(row)">
                                    <span>{{getValue(row.elementName,dataDict.channelGradeLevel1ElementDict) || row.elementName}}</span>
                                </a>
                                <a v-if="row.elementType === '2'" @click="change(row)">
                                    <span>{{getValue(row.elementName,dataDict.channelGradeElementDict) || row.elementName}}</span>
                                </a>
                                <!-- <a v-if="row.elementType === '2'" @click="config(row)" style="padding-left:5px;">配置</a> -->
                            </template>
                            <template slot-scope="{ row, index }" slot="action">
                                <Button type="primary" size="small" icon="md-add" @click="add(row)"></Button>
                                <Button type="error" size="small" icon="md-remove" @click="del(row)"></Button>
                                <Button v-if="row.elementType === '2'" type="primary" size="small" ghost @click="config(row)">配置</Button>
                            </template>
                        </Table>
                    </div>
                </Panel>
            </Collapse>

            <div class="back">
                <Button type="primary" @click="back">返回</Button>
            </div>
        </Card>
        <!-- <button @click="configModalOpen = true">配置评分要素</button> -->
        <Modal v-model="configModalOpen" fullscreen title="配置评分要素" footer-hide>
            <GradeModelConfig :modal="configModalOpen" :modalData="currentRow" :dataDict="dataDict" :modelCode="modelCode" @closeModal="closeModal" />
        </Modal>
        <IndicatorDetailsModal
            :getDataFn="getDataFn"
            :dataDict="dataDict"
            :modal="detailsModal"
            :modalTitle="modalTitle"
            :modalData="currentRow"
            :modelCode="modelCode"
            @closeModal="closeModal"
        />
        <IndicatorTypeModal
            :getDataFn="getDataFn"
            :dataDict="dataDict"
            :modal="typeModal"
            :modalTitle="modalTitle"
            :modalData="currentRow"
            :modelCode="modelCode"
            @closeModal="closeModal"
        />
    </div>
</template>

<script>
import GradeModelConfig from '../grade-model-config'

import { getDictDataList } from "_p/afs-channel/assets/js/utils";

import { getByModelCode, saveModelElement, editModelElement, deleteModelElement } from "_p/afs-channel/api/grade-model"

// 指标详情 弹窗
import IndicatorDetailsModal from "_p/afs-channel/pages/grade-model/components/indicatorDetailsModal"
// 指标分类 弹窗
import IndicatorTypeModal from "_p/afs-channel/pages/grade-model/components/indicatorTypeModal"

export default {
    // 评分模型列表
    name: 'GradeModelDetial',
    components: { GradeModelConfig, IndicatorDetailsModal, IndicatorTypeModal },
    data() {
        return {
            modelCode: null,
            configModalOpen: false,
            formData: {},
            pageParams: {},
            dicttArr: [
                "channelGradeElement", //名称 // 渠道评级二级指标
                "gradeModelType",
                "gradeModelStatus",
                "gradeModelElementType", // 指标种类
                "elementUse", // 指标使用方式
                "elementIgnore", // 指标是否忽略
                "timeDimension", //时间维度
                "channelGradeLevel1Element", // 渠道评级一级指标()
                "gradeDataSource", //  评分数据来源(gradeDataSource) 
            ],
            dataDict: {},
            openPanel: [1, 2,],
            getDataFn: () => { },
            detailsModal: false,
            typeModal: false,
            modalTitle: '',
            currentRow: {},
            loading: true,
            tableHead: [
                {
                    title: '名称',
                    key: 'elementName',
                    slot: "elementName",
                    tree: true,
                    minWidth: 200,
                    className: "slot-elementName",

                    renderHeader: (h, params) => {
                        return h('span', [
                            // h('span', '名称'),
                            h('span', params.column.title),
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small',
                                    icon: "md-add"
                                },
                                on: {
                                    click: () => {
                                        this.add()
                                    }
                                },
                                style: {
                                    marginLeft: '10px'
                                }
                            }),
                        ]);
                    }
                },
                {
                    title: '权重(%)',
                    key: 'elementWeight',
                    minWidth: 50
                },
                {
                    title: '满意值',
                    key: 'elementPlan',
                    minWidth: 50
                },
                {
                    title: '不允许值',
                    key: 'elementStand',
                    minWidth: 50
                },
                {
                    title: '指标要素',
                    key: 'elements',
                    minWidth: 200
                },
                {
                    title: "操作",
                    align: "center",
                    fixed: 'right',
                    slot: "action",
                    width: 160,
                },
            ],
            tableData: [],
        }
    },
    created() {
        this.getParams();
    },
    mounted() {
        this.init();
        console.group("页面初始数据：");
        console.log("pageParams:", this.pageParams);
        console.groupEnd();
    },
    methods: {
        init() {
            this.getDictDataList();
            this.getData()
        },
        // 获取初始数据
        getParams() {
            const pageParams = this.afs.getPageParams(this);
            this.pageParams = pageParams;
            this.modelCode = pageParams.modelCode
        },
        getDictDataList() {
            getDictDataList(this.dicttArr).then(res => {
                console.group("数据字典:");
                console.log(this.dicttArr.join("  "));
                console.log(JSON.parse(JSON.stringify(res)));
                console.groupEnd();
                this.dataDict = res;
            });
        },
        getData() {
            this.loading = true;
            const { modelCode } = this.pageParams
            getByModelCode(modelCode).then(res => {
                if (res.code === "0000") {
                    this.sortData(res.data);
                }
            })
        },
        // 整理
        sortData(data) {
            if (!data || !Array.isArray(data) || data.length <= 0) {
                this.tableData = [];
                this.loading = false;
                return;
            };
            // 一二级分类 特别注意 数据返回格式
            let firstLevel = this.getLevelData(data, '1'),
                secondLevel = this.getLevelData(data, '2'),
                tableData = [],
                _idx = 0;

            console.log('firstLevel', firstLevel);
            // console.log('secondLevel', secondLevel);
            firstLevel.forEach(ele => {
                const { attributes, id, state, text } = ele;
                let item = { id, state, text, children: [], _showChildren: true, _idx }
                tableData.push(Object.assign({}, item, attributes))
                _idx++;
            });
            secondLevel.forEach(ele => {
                const { attributes, id, state, text, pid } = ele;
                let item = { id, state, text, pid, _idx },
                    index = tableData.findIndex(e => e.elementNo === attributes.upElementNo);
                // console.log(index, 'index', ele);
                if (index >= 0) {
                    tableData[index].children.push(Object.assign({}, item, attributes))
                    _idx++;
                }
            })
            console.log(tableData, 'tableData')
            this.tableData = tableData;
            this.loading = false;
        },
        getLevelData(data, level) {
            if (!data || !level) return;
            return data.filter(e => e.attributes && e.attributes.elementType === level).sort((a, b) => a.attributes.seqno - b.attributes.seqno)
        },
        // 新增
        add(row) {
            this.getDataFn = saveModelElement

            if (!row) {
                this.currentRow = { elementType: '1' };
                this.modalTitle = "新增指标分类"
                this.typeModal = true;
            } else {
                let upElementNo = row.upElementNo ? row.upElementNo : row.elementNo
                this.currentRow = { elementType: '2', upElementNo };
                this.modalTitle = "新增指标详情"
                this.detailsModal = true;
            }
        },
        // 删除
        del(row) {
            if (!row) return;
            this.$Modal.confirm({
                title: "确认删除？",
                onOk: () => {
                    this.loading = true;
                    this.deleteQuery(row.modelCode, row.elementNo);
                }
            });
        },
        deleteQuery(modelCode, elementNo) {
            deleteModelElement(modelCode, elementNo).then(res => {
                if (res.code === "0000") {
                    this.$Message.success(res.data);
                    this.getData()
                } else {
                    this.loading = false;
                }
            }).catch(e => {
                console.error(e)
                this.loading = false;
            });
        },
        // 修改
        change(row) {
            if (!row && !row.elementType) return;
            this.currentRow = row;
            this.getDataFn = editModelElement;

            if (row.elementType === "1") {
                this.modalTitle = "修改指标分类"
                this.typeModal = true;
            } else if (row.elementType === "2") {
                this.modalTitle = "修改指标详情"
                this.detailsModal = true;
            }
        },
        getValue(value, dict) {
            if (!value || !dict) return;
            for (let i = 0; i < dict.length; i++) {
                if (value === dict[i].value)
                    return dict[i].title
            }
            return '';
        },
        // 配置
        config(row) {
            if (!row) return;
            this.currentRow = row
            this.configModalOpen = true
        },
        closeModal(reloadData) {
            this.detailsModal = false;
            this.typeModal = false;
            this.configModalOpen = false;
            this.getDataFn = () => { };

            if (reloadData)
                this.getData()
        },
        showSpin() {
            this.spinShow = true;
        },
        closeSpin() {
            this.spinShow = false;
        },
        back() {
            //关闭页面
            this.afs.closeTab(this);
        }
    }
}
</script>

<style lang="less">
.back {
    padding-top: 16px;
    text-align: center;
}
.text-center {
    text-align: center;
    button:not(:last-child) {
        margin-right: 16px;
    }
}
.slot-elementName > div {
    display: flex;
    flex-flow: row nowrap;
    justify-content: start;
    align-items: center;
}
</style>
